"""
钱包和交易记录模型
"""
from sqlalchemy import Column, String, Float, DateTime, Enum as SQLEnum, Text, Index
from app.core.database import Base
from datetime import datetime
import enum


class TransactionType(str, enum.Enum):
    """交易类型"""
    RECHARGE = "recharge"          # 充值
    WITHDRAW = "withdraw"          # 提现
    BOOKING_PAY = "booking_pay"    # 预约支付
    BOOKING_REFUND = "booking_refund"  # 预约退款
    SYSTEM_REWARD = "system_reward"    # 系统奖励
    TRANSFER_IN = "transfer_in"    # 转入
    TRANSFER_OUT = "transfer_out"  # 转出


class TransactionStatus(str, enum.Enum):
    """交易状态"""
    PENDING = "pending"    # 处理中
    SUCCESS = "success"    # 成功
    FAILED = "failed"      # 失败
    CANCELLED = "cancelled"  # 已取消


class Wallet(Base):
    """钱包表"""
    __tablename__ = "wallets"
    
    id = Column(String(32), primary_key=True, comment="钱包ID")
    user_id = Column(String(32), unique=True, index=True, nullable=False, comment="用户ID")
    balance = Column(Float, default=0.0, nullable=False, comment="余额")
    frozen_amount = Column(Float, default=0.0, nullable=False, comment="冻结金额")
    total_recharge = Column(Float, default=0.0, nullable=False, comment="累计充值")
    total_withdraw = Column(Float, default=0.0, nullable=False, comment="累计提现")
    total_spent = Column(Float, default=0.0, nullable=False, comment="累计消费")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    
    def to_dict(self):
        return {
            "id": self.id,
            "userId": self.user_id,
            "balance": self.balance,
            "frozenAmount": self.frozen_amount,
            "totalRecharge": self.total_recharge,
            "totalWithdraw": self.total_withdraw,
            "totalSpent": self.total_spent,
            "createdAt": self.created_at.isoformat() if self.created_at else None,
            "updatedAt": self.updated_at.isoformat() if self.updated_at else None
        }


class Transaction(Base):
    """交易记录表"""
    __tablename__ = "transactions"
    
    id = Column(String(32), primary_key=True, comment="交易ID")
    wallet_id = Column(String(32), index=True, nullable=False, comment="钱包ID")
    user_id = Column(String(32), index=True, nullable=False, comment="用户ID")
    type = Column(SQLEnum(TransactionType), nullable=False, comment="交易类型")
    amount = Column(Float, nullable=False, comment="交易金额")
    balance_before = Column(Float, nullable=False, comment="交易前余额")
    balance_after = Column(Float, nullable=False, comment="交易后余额")
    status = Column(SQLEnum(TransactionStatus), default=TransactionStatus.PENDING, comment="交易状态")
    description = Column(String(255), comment="交易描述")
    related_id = Column(String(32), comment="关联ID（如订单ID）")
    related_type = Column(String(50), comment="关联类型")
    payment_method = Column(String(50), comment="支付方式")
    payment_channel_order_no = Column(String(100), comment="支付渠道订单号")
    remark = Column(Text, comment="备注")
    created_at = Column(DateTime, default=datetime.now, index=True, comment="创建时间")
    completed_at = Column(DateTime, comment="完成时间")
    
    # 创建复合索引
    __table_args__ = (
        Index('idx_user_created', 'user_id', 'created_at'),
        Index('idx_wallet_type', 'wallet_id', 'type'),
        Index('idx_related', 'related_type', 'related_id'),
    )
    
    def to_dict(self):
        return {
            "id": self.id,
            "walletId": self.wallet_id,
            "userId": self.user_id,
            "type": self.type.value if self.type else None,
            "amount": self.amount,
            "balanceBefore": self.balance_before,
            "balanceAfter": self.balance_after,
            "status": self.status.value if self.status else None,
            "description": self.description,
            "relatedId": self.related_id,
            "relatedType": self.related_type,
            "paymentMethod": self.payment_method,
            "paymentChannelOrderNo": self.payment_channel_order_no,
            "remark": self.remark,
            "createdAt": self.created_at.isoformat() if self.created_at else None,
            "completedAt": self.completed_at.isoformat() if self.completed_at else None
        }

